//
//  CYMineViewController.m
//  cyjf
//
//  Created by tauCross on 2017/5/3.
//  Copyright © 2017年 Auto Financing. All rights reserved.
//

#import "CYMineViewController.h"

#import "CYMineSimpleInfoCell.h"
#import "CYMineActionCell.h"
#import "CYMineCapitalCell.h"
#import "CYEmptyCell.h"

#import "CYDataAPIUserAccountModel.h"

#import "CYCouponsViewController.h"
#import "CYRechargeViewController.h"
#import "CYSettingsViewController.h"
#import "CYMinePropertyViewController.h"
#import "CYWithdrawViewController.h"
#import "CYInvestRecordViewController.h"
#import "CYMainController.h"
#import "CYWebViewController.h"
#import "CYAboutUsViewController.h"
#import "CYContectUsViewController.h"
#import "CYMessageViewController.h"
#import "CYBillViewController.h"

#import <UIImageView+WebCache.h>



@interface CYMineViewController ()

@property(nonatomic, strong)UIView *topView;
@property(nonatomic, strong)UIImageView *avatarImageView;
@property(nonatomic, strong)UILabel *nicknameLabel;
@property(nonatomic, strong)UIButton *personButton;
@property(nonatomic, strong)UIButton *messageButton;
@property(nonatomic, strong)UILabel *messageBadge;

@property(nonatomic, strong)UIView *tableViewTopView;
@property(nonatomic, strong)CYMineSimpleInfoCellObject *infoCell;
@property(nonatomic, strong)CYMineCapitalCellObject *capitalCell;
@property(nonatomic, strong)CYMineActionCellObject *billCell;
@property(nonatomic, strong)CYMineActionCellObject *investRecordCell;
@property(nonatomic, strong)CYMineActionCellObject *couponCell;
@property(nonatomic, strong)CYMineActionCellObject *aboutUsCell;
@property(nonatomic, strong)CYMineActionCellObject *helpCell;
@property(nonatomic, strong)CYMineActionCellObject *serviceCell;
@property(nonatomic, strong)CYMineActionCellObject *settingsCell;

@property(nonatomic, strong)CYDataAPIUserAccountModel *apiModel;


@end


@implementation CYMineViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self loadDataFromServer];
}

- (void)onReceiveApplicationDidBecomeActiveNotification
{
    [self loadDataFromServer];
}

- (void)loadDataFromServer
{
    if(self.apiModel == nil)
    {
        [SVProgressHUD show];
    }
    @weakify(self);
    [CYStandardDataAPI user_userAccountWithComplete:^(CYResponse *response) {
        if(response.code == 0)
        {
            @strongify(self);
            self.apiModel = [CYDataAPIUserAccountModel mj_objectWithKeyValues:response.content];
            [SVProgressHUD dismiss];
        }
        else
        {
            if(self.apiModel == nil)
            {
                [SVProgressHUD showErrorWithStatus:response.message];
            }
            else
            {
                [SVProgressHUD dismiss];
            }
            if(response.code == 21013)
            {
                self.apiModel = nil;
                [[CYMainController standardController] goHome];
            }
        }
    }];
    [CYStandardDataAPI message_unreadCountWithType:CYDataAPIMessageTypePerson complete:^(CYResponse *response) {
        @strongify(self);
        if(response.code == 0)
        {
            if([response.content isKindOfClass:[NSNumber class]] && [response.content integerValue] > 0)
            {
                NSString *badge;
                if([response.content integerValue] > 9)
                {
                    badge = @"9+";
                }
                else
                {
                    badge = [response.content stringValue];
                }
                self.messageBadge.hidden = NO;
                self.messageBadge.text = badge;
                return;
            }
        }
        self.messageBadge.hidden = YES;
    }];
}

- (void)loadUI
{    
    self.topView = [[UIView alloc] init];
    self.topView.backgroundColor = [UIColor whiteColor];
    [self.contentView addSubview:self.topView];
    {
        self.avatarImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 22, 22)];
        self.avatarImageView.layer.masksToBounds = YES;
        self.avatarImageView.layer.cornerRadius = self.avatarImageView.height / 2;
        [self.topView addSubview:self.avatarImageView];
        
        self.nicknameLabel = [[UILabel alloc] init];
        self.nicknameLabel.font = [UIFont systemFontOfSize:14];
        self.nicknameLabel.textColor = HEXCOLOR(@"444444");
        [self.topView addSubview:self.nicknameLabel];
        
        self.personButton = [[UIButton alloc] init];
        [self.personButton addTarget:self action:@selector(onPersonButtonTouchUpInside) forControlEvents:UIControlEventTouchUpInside];
        [self.topView addSubview:self.personButton];
        
        self.messageButton = [[UIButton alloc] init];
        [self.messageButton addTarget:self action:@selector(onMessageButtonTouchUpInside) forControlEvents:UIControlEventTouchUpInside];
        [self.messageButton setImage:CYImage(@"mine_message") forState:UIControlStateNormal];
        [self.topView addSubview:self.messageButton];
        
        self.messageBadge = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 15, 15)];
        self.messageBadge.backgroundColor = APP_DEFAULT_COLOR_RED;
        self.messageBadge.textAlignment = NSTextAlignmentCenter;
        self.messageBadge.layer.masksToBounds = YES;
        self.messageBadge.layer.cornerRadius = self.messageBadge.height / 2;
        self.messageBadge.textColor = [UIColor whiteColor];
        self.messageBadge.font = [UIFont systemFontOfSize:10 weight:UIFontWeightRegular];
        self.messageBadge.hidden = YES;
        [self.topView addSubview:self.messageBadge];
    }
    
    self.tableViewTopView = [[UIView alloc] init];
    self.tableViewTopView.backgroundColor = [UIColor whiteColor];
    [self.tableView addSubview:self.tableViewTopView];

}

- (void)loadData
{
    @weakify(self);
    
    self.infoCell = [CYMineSimpleInfoCellObject objectWithCellClass:[CYMineSimpleInfoCell class]];
    
    self.capitalCell = [CYMineCapitalCellObject objectWithCellClass:[CYMineCapitalCell class]];
    self.capitalCell.rechargeAction = ^{
        [MobClick event:UM_EVENT_0045];
        @strongify(self);
        [self rechargeAction];
    };
    self.capitalCell.withdrawAction = ^{
        [MobClick event:UM_EVENT_0044];
        @strongify(self);
        [self withdrawAction];
    };
    
    self.billCell = [CYMineActionCellObject objectWithCellClass:[CYMineActionCell class]];
    self.billCell.icon = @"ico_person_money";
    self.billCell.title = @"资金记录";
    
    self.investRecordCell = [CYMineActionCellObject objectWithCellClass:[CYMineActionCell class]];
    self.investRecordCell.icon = @"mine_invest_record";
    self.investRecordCell.title = @"投资记录";
    
    self.couponCell = [CYMineActionCellObject objectWithCellClass:[CYMineActionCell class]];
    self.couponCell.icon = @"mine_coupons";
    self.couponCell.title = @"我的优惠券";
    
    self.aboutUsCell = [CYMineActionCellObject objectWithCellClass:[CYMineActionCell class]];
    self.aboutUsCell.icon = @"mine_about_us";
    self.aboutUsCell.title = @"关于我们";
    
    self.helpCell = [CYMineActionCellObject objectWithCellClass:[CYMineActionCell class]];
    self.helpCell.icon = @"mine_help";
    self.helpCell.title = @"帮助中心";
    
    self.serviceCell = [CYMineActionCellObject objectWithCellClass:[CYMineActionCell class]];
    self.serviceCell.icon = @"mine_service";
    self.serviceCell.title = @"联系客服";

    self.settingsCell = [CYMineActionCellObject objectWithCellClass:[CYMineActionCell class]];
    self.settingsCell.icon = @"mine_settings";
    self.settingsCell.title = @"设置";
    
    NSMutableArray *cells = [NSMutableArray array];
    {
        [cells addObject:self.infoCell];
    }
    {
        [cells addObject:self.capitalCell];
    }
    {
        CYEmptyCellObject *cell = [CYEmptyCellObject objectWithCellClass:[CYEmptyCell class]];
        cell.height = 10;
        [cells addObject:cell];
    }
    {
        [cells addObject:self.billCell];
    }
    {
        [cells addObject:self.investRecordCell];
    }
    {
        [cells addObject:self.couponCell];
        self.couponCell.isBottom = YES;
    }
    {
        CYEmptyCellObject *cell = [CYEmptyCellObject objectWithCellClass:[CYEmptyCell class]];
        cell.height = 10;
        [cells addObject:cell];
    }
    {
        [cells addObject:self.aboutUsCell];
    }
    {
        [cells addObject:self.helpCell];
    }
    {
        [cells addObject:self.serviceCell];
        self.serviceCell.isBottom = YES;
    }
    {
        CYEmptyCellObject *cell = [CYEmptyCellObject objectWithCellClass:[CYEmptyCell class]];
        cell.height = 10;
        [cells addObject:cell];
    }
    {
        [cells addObject:self.settingsCell];
        self.settingsCell.isBottom = YES;
    }
    
    self.tableModel = [[NIMutableTableViewModel alloc] initWithSectionedArray:cells delegate:(id)[NICellFactory class]];
    self.tableView.dataSource = self.tableModel;
    [self.tableView reloadData];
    
    [TCRACObserve(self, apiModel) subscribeNext:^(id x) {
        @strongify(self);
        [self.avatarImageView sd_setImageWithURL:self.apiModel.avatar.tc_url placeholderImage:CYImage(@"mine_avatar")];
        NSString *mobile = nil;
        if(self.apiModel.mobile.length == 11)
        {
            mobile = self.apiModel.mobile.cy_maskPhoneNumber;
        }
        self.nicknameLabel.text = mobile;
        [self layoutNicknameLabel];
        
        self.infoCell.totalBalance = SAFE_NUMBER(self.apiModel.allInterest).amountString;
        self.infoCell.availableBalance = SAFE_NUMBER(self.apiModel.walletTotle).amountString;
        self.infoCell.income = SAFE_NUMBER(self.apiModel.currentInterest).amountString;
        [self.tableView reloadData];
        
        self.billCell.hintText = SAFE_STRING(self.apiModel.walletInfo);
        
        NSNumber *coupon = SAFE_NUMBER(self.apiModel.soonToExpireCoupon);
        self.couponCell.hintDot = (coupon.integerValue > 0 && [self couponHint]);
        self.couponCell.hintText = coupon.integerValue > 0 ? [NSString stringWithFormat:@"%li张优惠券即将过期", coupon.longValue] : @"";
        
        if([self.apiModel.id isKindOfClass:[NSNumber class]])
        {
            CYStandardAuthManager.currentAuth.uid = self.apiModel.id;
            [CYStandardAuthManager saveAuth];
        }
    }];
}

- (void)layoutUI
{
    self.topView.width = self.contentView.width;
    self.topView.height = SAFE_TOP_HEIGHT;
    self.topView.left = 0;
    self.topView.top = 0;
    {
        self.avatarImageView.left = 20;
        self.avatarImageView.top = self.topView.height - 33;
        
        [self layoutNicknameLabel];
        
        self.personButton.width = 140;
        self.personButton.height = 44;
        self.personButton.left = 0;
        self.personButton.bottom = self.topView.height;
        
        self.messageButton.width = 62;
        self.messageButton.height = 44;
        self.messageButton.top = self.topView.height - 44;
        self.messageButton.right = self.topView.width;
        
        self.messageBadge.right = self.topView.width - 14;
        self.messageBadge.top = self.topView.height - 26;
    }
    
    self.tableView.width = self.contentView.width;
    self.tableView.height = self.contentView.height - self.topView.bottom;
    self.tableView.left = 0;
    self.tableView.top = self.topView.bottom;
    {
        self.tableViewTopView.width = self.tableView.width;
        self.tableViewTopView.height = SCREEN_HEIGHT;
        self.tableViewTopView.left = 0;
        self.tableViewTopView.bottom = 0;
    }

}

- (BOOL)prefersNavigationBarHidden
{
    return YES;
}

#pragma mark - Actions
- (void)couponsAction
{
    CYCouponsViewController *couponsViewContoller = [[CYCouponsViewController alloc] init];
    [self.navigationController pushViewController:couponsViewContoller animated:YES];
}

- (void)rechargeAction
{
    CYRechargeViewController *rechargeViewController = [[CYRechargeViewController alloc] init];
    [self.navigationController pushViewController:rechargeViewController animated:YES];
}

- (void)settingsAction
{
    CYSettingsViewController *settingsViewController = [[CYSettingsViewController alloc] init];
    [self.navigationController pushViewController:settingsViewController animated:YES];
}

- (void)minePropertyAction
{
    if(self.apiModel)
    {
        CYMinePropertyViewController *minePropertyViewController = [[CYMinePropertyViewController alloc] init];
        minePropertyViewController.totalProperty = self.apiModel.allInterest;
        minePropertyViewController.available = self.apiModel.walletTotle;
        minePropertyViewController.withdraw = self.apiModel.withdrawal;
        minePropertyViewController.waitCapital = self.apiModel.dueSumCapital;
        minePropertyViewController.waitInterest = self.apiModel.dueSumInterest;
        minePropertyViewController.totalInvest = self.apiModel.investTotal;
        minePropertyViewController.vipInvest = self.apiModel.vipMinInvest;
        [self.navigationController pushViewController:minePropertyViewController animated:YES];
    }
}

- (void)withdrawAction
{
    if(self.apiModel.bankCardNum.integerValue)
    {
        CYWithdrawViewController *withdrawViewController = [[CYWithdrawViewController alloc] init];
        [self.navigationController pushViewController:withdrawViewController animated:YES];
    }
    else
    {
        [SVProgressHUD showErrorWithStatus:@"未绑定银行卡"];
    }
}

- (void)investRecordAction
{
    CYInvestRecordViewController *investRecordViewController = [[CYInvestRecordViewController alloc] init];
    [self.navigationController pushViewController:investRecordViewController animated:YES];
}

- (void)aboutUsAction
{
    CYAboutUsViewController *aboutUsViewController = [[CYAboutUsViewController alloc] init];
    [self.navigationController pushViewController:aboutUsViewController animated:YES];
}

- (void)serviceAction
{
    CYContectUsViewController *contectUsViewController = [[CYContectUsViewController alloc] init];
    [self.navigationController pushViewController:contectUsViewController animated:YES];
}

- (void)billAction
{
    CYBillViewController *billViewController = [[CYBillViewController alloc] init];
    [self.navigationController pushViewController:billViewController animated:YES];
}

- (void)helpAction
{
    CYWebViewController *webViewController = [[CYWebViewController alloc] init];
    webViewController.url = [CY_H5_BASE_URL stringByAppendingString:@"views/help_center.html"];
    [self.navigationController pushViewController:webViewController animated:YES];
}

- (void)inviteAction
{
    CYWebViewController *webViewController = [[CYWebViewController alloc] init];
    webViewController.url = [CY_H5_BASE_URL stringByAppendingString:@"views/friends.html"];
    [self.navigationController pushViewController:webViewController animated:YES];
}

- (void)messageAction
{
    CYMessageViewController *messageViewController = [[CYMessageViewController alloc] init];
    [self.navigationController pushViewController:messageViewController animated:YES];
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NICellObject *cellObject = [self.tableModel objectAtIndexPath:indexPath];
    if(cellObject == self.infoCell)
    {
        [MobClick event:UM_EVENT_0043];
        [self minePropertyAction];
        return;
    }
    if(cellObject == self.settingsCell)
    {
        [MobClick event:UM_EVENT_0051];
        [self settingsAction];
        return;
    }
    if(cellObject == self.investRecordCell)
    {
        [MobClick event:UM_EVENT_0046];
        [self investRecordAction];
        return;
    }
    if(cellObject == self.couponCell)
    {
        [MobClick event:UM_EVENT_0047];
        [self couponsAction];
        [self tagCouponHint];
        return;
    }
    if(cellObject == self.aboutUsCell)
    {
        [MobClick event:UM_EVENT_0048];
        [self aboutUsAction];
        return;
    }
    if(cellObject == self.helpCell)
    {
        [MobClick event:UM_EVENT_0049];
        [self helpAction];
        return;
    }
    if(cellObject == self.serviceCell)
    {
        [MobClick event:UM_EVENT_0050];
        [self serviceAction];
        return;
    }
    if(cellObject == self.billCell)
    {
        [self billAction];
        return;
    }
}

#pragma mark - Control Events
- (void)onPersonButtonTouchUpInside
{
    
}

- (void)onMessageButtonTouchUpInside
{
    [MobClick event:UM_EVENT_0042];
    [self messageAction];
}

#pragma mark - Private Method
- (void)layoutNicknameLabel
{
    [self.nicknameLabel sizeToFit];
    self.nicknameLabel.centerY = self.avatarImageView.centerY;
    self.nicknameLabel.left = 46;
}

- (BOOL)couponHint
{
    NSDictionary *mine_coupon_hint = [[NSUserDefaults standardUserDefaults] dictionaryForKey:@"mine_coupon_hint"];
    if(![mine_coupon_hint isKindOfClass:[NSDictionary class]])
    {
        mine_coupon_hint = [NSDictionary dictionary];
    }
    if(CYStandardAuthManager.currentAuth.uid && mine_coupon_hint[CYStandardAuthManager.currentAuth.uid.stringValue] && [mine_coupon_hint[CYStandardAuthManager.currentAuth.uid.stringValue] isEqualToString:[[NSDate date] cy_stringWithFormat:@"yyyy-MM-dd"]])
    {
        return NO;
    }
    return YES;
}

- (void)tagCouponHint
{
    NSDictionary *mine_coupon_hint = [[NSUserDefaults standardUserDefaults] dictionaryForKey:@"mine_coupon_hint"];
    if(![mine_coupon_hint isKindOfClass:[NSDictionary class]])
    {
        mine_coupon_hint = [NSDictionary dictionary];
    }
    NSMutableDictionary *m = [NSMutableDictionary dictionaryWithDictionary:mine_coupon_hint];
    if(CYStandardAuthManager.currentAuth.uid)
    {
        m[CYStandardAuthManager.currentAuth.uid.stringValue] = [[NSDate date] cy_stringWithFormat:@"yyyy-MM-dd"];
        [[NSUserDefaults standardUserDefaults] setObject:m forKey:@"mine_coupon_hint"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}

@end
